<?php
namespace App\Models\Account;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;
use DB;
use \Illuminate\Support\Facades\Input;


class PlayerOnline extends  Model{
    public function paginate()
    {
        $perPage = 20;

        $page = Request::get('page', 1);
        $area = Request::get('area', 1);

        $start = ($page-1)*$perPage;
        $data = self::GetOnlinePlayerList($area, $page, $perPage);
        extract($data['data'] ?: []);

        if (is_array($data)) {
            foreach ($data as $key => &$obj) {
                $obj['is_robot'] = $obj['account'] < 50000 ? "YES" : "NO";
                if ($obj['is_robot'] == 'YES') {
                    unset($data[$key]);
                }
            }
        }
        $movies = static::hydrate($data?:[]);
        // $data['total'] = 100;
        \Log::debug(__METHOD__, [$data, $count]);
        $paginator = new LengthAwarePaginator($movies, $count, $perPage);
        $paginator->setPath(url()->current());
        // var_dump($paginator);exit;
        return $paginator;

    }

    // 获取在线玩家列表
    public static function GetOnlinePlayerList($area, $page = 0, $page_size = 20)
    {
        if (empty($page) ) {
            $page = 1;
        }
        $data['offset'] = ($page - 1) * $page_size;
        $data['limit'] = $page_size;
        $rtn_info = [];
        \App\Models\SendSocketToGame::SendAction(function($socket)use(&$rtn_info, $data, $area){
            $msg['msgid'] = \App\Service\MessageDef::http_plat_game_request;
            $msg["area"] = intval($area);
            $msg['game_msgid'] = \App\Service\MessageDef::g2p_player_list_req;
            $msg["playerId"] = 1;
            $msg["game_msg"] = [
                'offset' => $data['offset'],
                'limit'  => $data['limit'],
            ];
            $ret = $socket->send($msg);
            
            $rtn_info = $socket->ReadHttpReponse();
            // \Log::debug('get player online list info', [$rtn_info]);
            //\Log::debug('read mail reponse data', [$msg,$rtn_info]);
        });
        //var_dump($rtn_info);exit;
        if (empty($rtn_info)) {
            $rtn_info = ['data' => [], 'count' => 0];
        }
        return $rtn_info;
    }
    public static function SourceCondition(&$rw)
    {
        $cond = Request::all();
        if ($cond['area']){
            $rw->where("area", 'like', $cond["area"].'%');
        }

    }
}
